# -*- coding: utf-8 -*-
# coding:utf-8
import os
import wejudge.kernel.general as kernel
import django.core.urlresolvers
import subprocess

__author__ = 'lancelrq'


class Helper(kernel.ViewerFramework):

    def __init__(self, request):
        kernel.ViewerFramework.__init__(self, request)
        self._navbar_action = "helper"

    def index(self):
        self._template_file = "helper/index.html"
        self._context = {
            'helper_action': 'index'
        }

    def StudentGuide(self):
        self._template_file = "helper/student_guide.html"
        self._context = {
            'helper_action': 'student_guide'
        }

    def StudentGuideViewer(self, vindex):
        self._template_file = "helper/student_guide/%s.html" % vindex

    def code_formatter(self):
        code = ""
        if self._request.method.upper() == 'POST':
            code = self._request.POST.get('code', '')
            ajax = self._request.GET.get('ajax', '')
            if code != '':
                code = self._code_formatter(code)
            if ajax == '1':
                self._action = kernel.const.VIEW_ACTION_JSON
                self._result = kernel.RESTStruct(True, data={
                    "code": code
                })
                return
        self._template_file = "helper/code_formatter.html"
        self._context = {
            "code": code
        }

    def _code_formatter(self, code):
        ps = subprocess.Popen(
            "indent -bad -bap -bbb -bbo -nbc -bl -bli0 -bls -c33 -cd33 -ncdb -ncdw -nce "
            "-cli0 -cp33 -cs -d0 -nbfda -nfc1 -nfca -hnl -ip5 -l75 -lp -npcs -nprs -saf "
            "-sai -saw -nsc -nsob -nss -i4 -ts4 -ut -npsl",
             shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE
        )
        code = code.replace("\r\n", "\n").replace("\r", "\n")
        ps.stdin.write(code)
        ps.stdin.close()
        output = ps.stdout.read()
        return output